{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_3a0i46j",
    "id": "44C527C86C2941789DE841DE4A782754",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 过拟合、欠拟合及其解决方案\n",
    "1. 过拟合、欠拟合的概念\n",
    "2. 权重衰减\n",
    "3. 丢弃法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "id": "B581E99B8732453B805914BCA97D6928",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import os\n",
    "# cp_str = 'cp -r /home/kesci/input/d2lzh1981 /home/kesci/work'\n",
    "# os.system(cp_str)\n",
    "# tar_str = 'tar czvf /home/kesci/work/d2lzh1981.tar /home/kesci/work/d2lzh1981'\n",
    "# os.system(tar_str)\n",
    "# print('finish')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_2rrhvg5",
    "id": "1C7884059BD2464DB639268E872E99C2",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 模型选择、过拟合和欠拟合\n",
    "\n",
    "## 训练误差和泛化误差\n",
    "在解释上述现象之前，我们需要区分训练误差（training error）和泛化误差（generalization error）。通俗来讲，前者指模型在训练数据集上表现出的误差，后者指模型在任意一个测试数据样本上表现出的误差的期望，并常常通过测试数据集上的误差来近似。计算训练误差和泛化误差可以使用之前介绍过的损失函数，例如线性回归用到的平方损失函数和softmax回归用到的交叉熵损失函数。\n",
    "\n",
    "机器学习模型应关注降低泛化误差。\n",
    "\n",
    "## 模型选择\n",
    "### 验证数据集\n",
    "从严格意义上讲，测试集只能在所有超参数和模型参数选定后使用一次。不可以使用测试数据选择模型，如调参。由于无法从训练误差估计泛化误差，因此也不应只依赖训练数据选择模型。鉴于此，我们可以预留一部分在训练数据集和测试数据集以外的数据来进行模型选择。这部分数据被称为验证数据集，简称验证集（validation set）。例如，我们可以从给定的训练集中随机选取一小部分作为验证集，而将剩余部分作为真正的训练集。\n",
    "\n",
    "### K折交叉验证  \n",
    "由于验证数据集不参与模型训练，当训练数据不够用时，预留大量的验证数据显得太奢侈。一种改善的方法是K折交叉验证（K-fold cross-validation）。在K折交叉验证中，我们把原始训练数据集分割成K个不重合的子数据集，然后我们做K次模型训练和验证。每一次，我们使用一个子数据集验证模型，并使用其他K-1个子数据集来训练模型。在这K次训练和验证中，每次用来验证模型的子数据集都不同。最后，我们对这K次训练误差和验证误差分别求平均。\n",
    "## 过拟合和欠拟合\n",
    "接下来，我们将探究模型训练中经常出现的两类典型问题：\n",
    "- 一类是模型无法得到较低的训练误差，我们将这一现象称作欠拟合（underfitting）；\n",
    "- 另一类是模型的训练误差远小于它在测试数据集上的误差，我们称该现象为过拟合（overfitting）。\n",
    "在实践中，我们要尽可能同时应对欠拟合和过拟合。虽然有很多因素可能导致这两种拟合问题，在这里我们重点讨论两个因素：模型复杂度和训练数据集大小。\n",
    "\n",
    "### 模型复杂度\n",
    "为了解释模型复杂度，我们以多项式函数拟合为例。给定一个由标量数据特征$x$和对应的标量标签$y$组成的训练数据集，多项式函数拟合的目标是找一个$K$阶多项式函数\n",
    "\n",
    "\n",
    "$$\n",
    " \\hat{y} = b + \\sum_{k=1}^K x^k w_k \n",
    "$$\n",
    "\n",
    "\n",
    "来近似 $y$。在上式中，$w_k$是模型的权重参数，$b$是偏差参数。与线性回归相同，多项式函数拟合也使用平方损失函数。特别地，一阶多项式函数拟合又叫线性函数拟合。\n",
    "\n",
    "给定训练数据集，模型复杂度和误差之间的关系：\n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5jc27wxoj.png?imageView2/0/w/960/h/960)\n",
    "\n",
    "### 训练数据集大小\n",
    "影响欠拟合和过拟合的另一个重要因素是训练数据集的大小。一般来说，如果训练数据集中样本数过少，特别是比模型参数数量（按元素计）更少时，过拟合更容易发生。此外，泛化误差不会随训练数据集里样本数量增加而增大。因此，在计算资源允许的范围之内，我们通常希望训练数据集大一些，特别是在模型复杂度较高时，例如层数较多的深度学习模型。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_rxqm2hz",
    "id": "662A794758DD42EFA08B79C1EF032C65",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 多项式函数拟合实验"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
    "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
    "graffitiCellId": "id_yjb9esq",
    "id": "F39C60E42E09441D8602243557564E0A",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.4.0\n"
     ]
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "import torch\n",
    "import numpy as np\n",
    "import sys\n",
    "sys.path.append(\"..\")\n",
    "import d2lzh1981 as d2l\n",
    "print(torch.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_1aakii8",
    "id": "193FB89ACE2E4D4888FB258A250939AD",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 初始化模型参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "_cell_guid": "79c7e3d0-c299-4dcb-8224-4455121ee9b0",
    "_uuid": "d629ff2d2480ee46fbb7e2d37f6b5fab8052498a",
    "graffitiCellId": "id_3xv7jo8",
    "id": "9714C0B5EF3344AB89F6C05008E10951",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "n_train, n_test, true_w, true_b = 100, 100, [1.2, -3.4, 5.6], 5\n",
    "features = torch.randn((n_train + n_test, 1))\n",
    "poly_features = torch.cat((features, torch.pow(features, 2), torch.pow(features, 3)), 1) \n",
    "labels = (true_w[0] * poly_features[:, 0] + true_w[1] * poly_features[:, 1]\n",
    "          + true_w[2] * poly_features[:, 2] + true_b)\n",
    "labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "graffitiCellId": "id_m2mu8wo",
    "id": "FDF06E080C72455296FF40E5A03C8A1D",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([[-0.8589],\n",
       "         [-0.2534]]), tensor([[-0.8589,  0.7377, -0.6335],\n",
       "         [-0.2534,  0.0642, -0.0163]]), tensor([-2.0794,  4.4039]))"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "features[:2], poly_features[:2], labels[:2]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_6fb98pt",
    "id": "04AB33FA366C42CDBF58FE28874F3F27",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 定义、训练和测试模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "graffitiCellId": "id_tq07955",
    "id": "DD5CB5E380BE4BF498E4F3D5A9F97F43",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def semilogy(x_vals, y_vals, x_label, y_label, x2_vals=None, y2_vals=None,\n",
    "             legend=None, figsize=(3.5, 2.5)):\n",
    "    # d2l.set_figsize(figsize)\n",
    "    d2l.plt.xlabel(x_label)\n",
    "    d2l.plt.ylabel(y_label)\n",
    "    d2l.plt.semilogy(x_vals, y_vals)\n",
    "    if x2_vals and y2_vals:\n",
    "        d2l.plt.semilogy(x2_vals, y2_vals, linestyle=':')\n",
    "        d2l.plt.legend(legend)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "graffitiCellId": "id_3lzy7bj",
    "id": "3DA4335947C44C018CD2C8B215A641ED",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "num_epochs, loss = 100, torch.nn.MSELoss()\n",
    "\n",
    "def fit_and_plot(train_features, test_features, train_labels, test_labels):\n",
    "    # 初始化网络模型\n",
    "    net = torch.nn.Linear(train_features.shape[-1], 1)\n",
    "    # 通过Linear文档可知，pytorch已经将参数初始化了，所以我们这里就不手动初始化了\n",
    "    \n",
    "    # 设置批量大小\n",
    "    batch_size = min(10, train_labels.shape[0])    \n",
    "    dataset = torch.utils.data.TensorDataset(train_features, train_labels)      # 设置数据集\n",
    "    train_iter = torch.utils.data.DataLoader(dataset, batch_size, shuffle=True) # 设置获取数据方式\n",
    "    \n",
    "    optimizer = torch.optim.SGD(net.parameters(), lr=0.01)                      # 设置优化函数，使用的是随机梯度下降优化\n",
    "    train_ls, test_ls = [], []\n",
    "    for _ in range(num_epochs):\n",
    "        for X, y in train_iter:                                                 # 取一个批量的数据\n",
    "            l = loss(net(X), y.view(-1, 1))                                     # 输入到网络中计算输出，并和标签比较求得损失函数\n",
    "            optimizer.zero_grad()                                               # 梯度清零，防止梯度累加干扰优化\n",
    "            l.backward()                                                        # 求梯度\n",
    "            optimizer.step()                                                    # 迭代优化函数，进行参数优化\n",
    "        train_labels = train_labels.view(-1, 1)\n",
    "        test_labels = test_labels.view(-1, 1)\n",
    "        train_ls.append(loss(net(train_features), train_labels).item())         # 将训练损失保存到train_ls中\n",
    "        test_ls.append(loss(net(test_features), test_labels).item())            # 将测试损失保存到test_ls中\n",
    "    print('final epoch: train loss', train_ls[-1], 'test loss', test_ls[-1])    \n",
    "    semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'loss',\n",
    "             range(1, num_epochs + 1), test_ls, ['train', 'test'])\n",
    "    print('weight:', net.weight.data,\n",
    "          '\\nbias:', net.bias.data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_tvv0n31",
    "id": "FEBABF4CE4FC49F8869E557513F6CFD8",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 三阶多项式函数拟合（正常）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "graffitiCellId": "id_pc28vr5",
    "id": "CD685B472B744329A1CFC47C9F0B5E89",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "final epoch: train loss 8887.298828125 test loss 1145.94287109375\n",
      "weight: tensor([[-8.5120, 19.0351, 12.8616]]) \n",
      "bias: tensor([-5.4607])\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<img src=\"https://cdn.kesci.com/rt_upload/CD685B472B744329A1CFC47C9F0B5E89/q5jf5azjcn.png\">"
      ],
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fit_and_plot(poly_features[:n_train, :], poly_features[n_train:, :], labels[:n_train], labels[n_train:])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_pu3gps2",
    "id": "F5C7FE5EF88D44FE85E0B651B3B09959",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 线性函数拟合（欠拟合）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "graffitiCellId": "id_07e409i",
    "id": "33AD626DA0B94DB7A28D47697312B45D",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "final epoch: train loss 781.689453125 test loss 329.79852294921875\n",
      "weight: tensor([[26.8753]]) \n",
      "bias: tensor([6.1426])\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<img src=\"https://cdn.kesci.com/rt_upload/33AD626DA0B94DB7A28D47697312B45D/q5jf5al2tv.png\">"
      ],
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fit_and_plot(features[:n_train, :], features[n_train:, :], labels[:n_train], labels[n_train:])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_hmoo3h2",
    "id": "BC253732133341DC8F028FB6834C68F0",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 训练样本不足（过拟合）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "graffitiCellId": "id_h1gobje",
    "id": "AB13F65A70A9484788F8004E427EC290",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "final epoch: train loss 6.23520565032959 test loss 409.9844665527344\n",
      "weight: tensor([[ 0.9729, -0.9612,  0.7259]]) \n",
      "bias: tensor([1.6334])\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<img src=\"https://cdn.kesci.com/rt_upload/AB13F65A70A9484788F8004E427EC290/q5jf5bd11u.png\">"
      ],
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fit_and_plot(poly_features[0:2, :], poly_features[n_train:, :], labels[0:2], labels[n_train:])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_4tfoquk",
    "id": "A1A8C28C0A204B04AD8B5FFF9C2D2F5B",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 权重衰减\n",
    "## 方法  \n",
    "权重衰减等价于 $L_2$ 范数正则化（regularization）。正则化通过为模型损失函数添加惩罚项使学出的模型参数值较小，是应对过拟合的常用手段。\n",
    "\n",
    "##  L2 范数正则化（regularization）\n",
    "$L_2$范数正则化在模型原损失函数基础上添加$L_2$范数惩罚项，从而得到训练所需要最小化的函数。$L_2$范数惩罚项指的是模型权重参数每个元素的平方和与一个正的常数的乘积。以线性回归中的线性回归损失函数为例\n",
    "\n",
    "\n",
    "$$\n",
    " \\ell(w_1, w_2, b) = \\frac{1}{n} \\sum_{i=1}^n \\frac{1}{2}\\left(x_1^{(i)} w_1 + x_2^{(i)} w_2 + b - y^{(i)}\\right)^2 \n",
    "$$\n",
    "\n",
    "\n",
    "其中$w_1, w_2$是权重参数，$b$是偏差参数，样本$i$的输入为$x_1^{(i)}, x_2^{(i)}$，标签为$y^{(i)}$，样本数为$n$。将权重参数用向量$\\boldsymbol{w} = [w_1, w_2]$表示，带有$L_2$范数惩罚项的新损失函数为\n",
    "\n",
    "\n",
    "$$\n",
    "\\ell(w_1, w_2, b) + \\frac{\\lambda}{2n} |\\boldsymbol{w}|^2,\n",
    "$$\n",
    "\n",
    "\n",
    "其中超参数$\\lambda > 0$。当权重参数均为0时，惩罚项最小。当$\\lambda$较大时，惩罚项在损失函数中的比重较大，这通常会使学到的权重参数的元素较接近0。当$\\lambda$设为0时，惩罚项完全不起作用。上式中$L_2$范数平方$|\\boldsymbol{w}|^2$展开后得到$w_1^2 + w_2^2$。\n",
    "有了$L_2$范数惩罚项后，在小批量随机梯度下降中，我们将线性回归一节中权重$w_1$和$w_2$的迭代方式更改为\n",
    "\n",
    "\n",
    "$$\n",
    " \\begin{aligned} w_1 &\\leftarrow \\left(1- \\frac{\\eta\\lambda}{|\\mathcal{B}|} \\right)w_1 - \\frac{\\eta}{|\\mathcal{B}|} \\sum_{i \\in \\mathcal{B}}x_1^{(i)} \\left(x_1^{(i)} w_1 + x_2^{(i)} w_2 + b - y^{(i)}\\right),\\\\ w_2 &\\leftarrow \\left(1- \\frac{\\eta\\lambda}{|\\mathcal{B}|} \\right)w_2 - \\frac{\\eta}{|\\mathcal{B}|} \\sum_{i \\in \\mathcal{B}}x_2^{(i)} \\left(x_1^{(i)} w_1 + x_2^{(i)} w_2 + b - y^{(i)}\\right). \\end{aligned} \n",
    "$$\n",
    "\n",
    "\n",
    "可见，$L_2$范数正则化令权重$w_1$和$w_2$先自乘小于1的数，再减去不含惩罚项的梯度。因此，$L_2$范数正则化又叫权重衰减。权重衰减通过惩罚绝对值较大的模型参数为需要学习的模型增加了限制，这可能对过拟合有效。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_6r7el1m",
    "id": "86B363E2493A4A2980C5E00729B925F5",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 高维线性回归实验从零开始的实现\n",
    "下面，我们以高维线性回归为例来引入一个过拟合问题，并使用权重衰减来应对过拟合。设数据样本特征的维度为$p$。对于训练数据集和测试数据集中特征为$x_1, x_2, \\ldots, x_p$的任一样本，我们使用如下的线性函数来生成该样本的标签：\n",
    "\n",
    "\n",
    "$$\n",
    " y = 0.05 + \\sum_{i = 1}^p 0.01x_i + \\epsilon \n",
    "$$\n",
    "\n",
    "\n",
    "其中噪声项$\\epsilon$服从均值为0、标准差为0.01的正态分布。为了较容易地观察过拟合，我们考虑高维线性回归问题，如设维度$p=200$；同时，我们特意把训练数据集的样本数设低，如20。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "graffitiCellId": "id_m6mthxc",
    "id": "51E803AFA42047D48605A9042CD266F8",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.4.0\n"
     ]
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import numpy as np\n",
    "import sys\n",
    "sys.path.append(\"..\")\n",
    "import d2lzh1981 as d2l\n",
    "\n",
    "print(torch.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_d4sywej",
    "id": "5AC8DFCEDD734B8289B2CE7D06C82B6F",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 初始化模型参数\n",
    "与前面观察过拟合和欠拟合现象的时候相似，在这里不再解释。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "graffitiCellId": "id_3ymafxv",
    "id": "D66AE4FB939640948F151F6FF7C1740E",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "n_train, n_test, num_inputs = 20, 100, 200\n",
    "true_w, true_b = torch.ones(num_inputs, 1) * 0.01, 0.05\n",
    "\n",
    "features = torch.randn((n_train + n_test, num_inputs))\n",
    "labels = torch.matmul(features, true_w) + true_b\n",
    "labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)\n",
    "train_features, test_features = features[:n_train, :], features[n_train:, :]\n",
    "train_labels, test_labels = labels[:n_train], labels[n_train:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "graffitiCellId": "id_xd0w3ub",
    "id": "E1707F6923A742F69F84896E84B463FE",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 定义参数初始化函数，初始化模型参数并且附上梯度\n",
    "def init_params():\n",
    "    w = torch.randn((num_inputs, 1), requires_grad=True)\n",
    "    b = torch.zeros(1, requires_grad=True)\n",
    "    return [w, b]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_ejz9flm",
    "id": "01F0DAF1CD6F48BA92BAAE9F7554EA28",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 定义L2范数惩罚项"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "graffitiCellId": "id_kkiguji",
    "id": "4709112E91504EF68681066730402A03",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def l2_penalty(w):\n",
    "    return (w**2).sum() / 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_99qaypt",
    "id": "06C980C7C2534A728058234C02210A34",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 定义训练和测试"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "graffitiCellId": "id_6crgl61",
    "id": "3A369C128AE64990854186DAD85DDD7F",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "batch_size, num_epochs, lr = 1, 100, 0.003\n",
    "net, loss = d2l.linreg, d2l.squared_loss\n",
    "\n",
    "dataset = torch.utils.data.TensorDataset(train_features, train_labels)\n",
    "train_iter = torch.utils.data.DataLoader(dataset, batch_size, shuffle=True)\n",
    "\n",
    "def fit_and_plot(lambd):\n",
    "    w, b = init_params()\n",
    "    train_ls, test_ls = [], []\n",
    "    for _ in range(num_epochs):\n",
    "        for X, y in train_iter:\n",
    "            # 添加了L2范数惩罚项\n",
    "            l = loss(net(X, w, b), y) + lambd * l2_penalty(w)\n",
    "            l = l.sum()\n",
    "            \n",
    "            if w.grad is not None:\n",
    "                w.grad.data.zero_()\n",
    "                b.grad.data.zero_()\n",
    "            l.backward()\n",
    "            d2l.sgd([w, b], lr, batch_size)\n",
    "        train_ls.append(loss(net(train_features, w, b), train_labels).mean().item())\n",
    "        test_ls.append(loss(net(test_features, w, b), test_labels).mean().item())\n",
    "    d2l.semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'loss',\n",
    "                 range(1, num_epochs + 1), test_ls, ['train', 'test'])\n",
    "    print('L2 norm of w:', w.norm().item())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_55gl5e9",
    "id": "BA54CB5FD4E64380AC1357E8537265DC",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 观察过拟合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "graffitiCellId": "id_6pmjf6b",
    "id": "C27406AAA0FD41C6801D55ED4B25D5EA",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "L2 norm of w: 11.6444091796875\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<img src=\"https://cdn.kesci.com/rt_upload/C27406AAA0FD41C6801D55ED4B25D5EA/q5jf5cs7lp.svg\">"
      ],
      "text/plain": [
       "<Figure size 252x180 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fit_and_plot(lambd=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_ejl383l",
    "id": "F2335EC469AB402C890CE258932583D1",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 使用权重衰减"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "graffitiCellId": "id_x1tkbn7",
    "id": "0770D8C23B8144C59D13D24390E471F0",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "L2 norm of w: 0.04063604772090912\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<img src=\"https://cdn.kesci.com/rt_upload/0770D8C23B8144C59D13D24390E471F0/q5jf5d4mwp.svg\">"
      ],
      "text/plain": [
       "<Figure size 252x180 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fit_and_plot(lambd=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_g2d3ly2",
    "id": "FD1464A14A6149AB81CF443A10F843A4",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 简洁实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "graffitiCellId": "id_b6kxfkc",
    "id": "20CFA1339D054931892561E254150368",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def fit_and_plot_pytorch(wd):\n",
    "    # 对权重参数衰减。权重名称一般是以weight结尾\n",
    "    net = nn.Linear(num_inputs, 1)\n",
    "    nn.init.normal_(net.weight, mean=0, std=1)\n",
    "    nn.init.normal_(net.bias, mean=0, std=1)\n",
    "    optimizer_w = torch.optim.SGD(params=[net.weight], lr=lr, weight_decay=wd) # 对权重参数衰减\n",
    "    optimizer_b = torch.optim.SGD(params=[net.bias], lr=lr)  # 不对偏差参数衰减\n",
    "    \n",
    "    train_ls, test_ls = [], []\n",
    "    for _ in range(num_epochs):\n",
    "        for X, y in train_iter:\n",
    "            l = loss(net(X), y).mean()\n",
    "            optimizer_w.zero_grad()\n",
    "            optimizer_b.zero_grad()\n",
    "            \n",
    "            l.backward()\n",
    "            \n",
    "            # 对两个optimizer实例分别调用step函数，从而分别更新权重和偏差\n",
    "            optimizer_w.step()\n",
    "            optimizer_b.step()\n",
    "        train_ls.append(loss(net(train_features), train_labels).mean().item())\n",
    "        test_ls.append(loss(net(test_features), test_labels).mean().item())\n",
    "    d2l.semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'loss',\n",
    "                 range(1, num_epochs + 1), test_ls, ['train', 'test'])\n",
    "    print('L2 norm of w:', net.weight.data.norm().item())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "graffitiCellId": "id_dxnud8x",
    "id": "525D01167F0E40509495588D6B0A0FB9",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "L2 norm of w: 13.361410140991211\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<img src=\"https://cdn.kesci.com/rt_upload/525D01167F0E40509495588D6B0A0FB9/q5jf5e5i21.svg\">"
      ],
      "text/plain": [
       "<Figure size 252x180 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fit_and_plot_pytorch(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "graffitiCellId": "id_qclwxdh",
    "id": "3FAACA854B9545A8ADADDEB6EE17A680",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "L2 norm of w: 0.051789578050374985\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<img src=\"https://cdn.kesci.com/rt_upload/3FAACA854B9545A8ADADDEB6EE17A680/q5jf5fa51u.svg\">"
      ],
      "text/plain": [
       "<Figure size 252x180 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fit_and_plot_pytorch(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_c8j5g7h",
    "id": "3547FD2B0E60465BB11AA6BADF4AC288",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 丢弃法\n",
    "\n",
    "多层感知机中神经网络图描述了一个单隐藏层的多层感知机。其中输入个数为4，隐藏单元个数为5，且隐藏单元$h_i$（$i=1, \\ldots, 5$）的计算表达式为\n",
    "\n",
    "\n",
    "$$\n",
    " h_i = \\phi\\left(x_1 w_{1i} + x_2 w_{2i} + x_3 w_{3i} + x_4 w_{4i} + b_i\\right) \n",
    "$$\n",
    "\n",
    "\n",
    "这里$\\phi$是激活函数，$x_1, \\ldots, x_4$是输入，隐藏单元$i$的权重参数为$w_{1i}, \\ldots, w_{4i}$，偏差参数为$b_i$。当对该隐藏层使用丢弃法时，该层的隐藏单元将有一定概率被丢弃掉。设丢弃概率为$p$，那么有$p$的概率$h_i$会被清零，有$1-p$的概率$h_i$会除以$1-p$做拉伸。丢弃概率是丢弃法的超参数。具体来说，设随机变量$\\xi_i$为0和1的概率分别为$p$和$1-p$。使用丢弃法时我们计算新的隐藏单元$h_i'$\n",
    "\n",
    "\n",
    "$$\n",
    " h_i' = \\frac{\\xi_i}{1-p} h_i \n",
    "$$\n",
    "\n",
    "\n",
    "由于$E(\\xi_i) = 1-p$，因此\n",
    "\n",
    "\n",
    "$$\n",
    " E(h_i') = \\frac{E(\\xi_i)}{1-p}h_i = h_i \n",
    "$$\n",
    "\n",
    "\n",
    "即丢弃法不改变其输入的期望值。让我们对之前多层感知机的神经网络中的隐藏层使用丢弃法，一种可能的结果如图所示，其中$h_2$和$h_5$被清零。这时输出值的计算不再依赖$h_2$和$h_5$，在反向传播时，与这两个隐藏单元相关的权重的梯度均为0。由于在训练中隐藏层神经元的丢弃是随机的，即$h_1, \\ldots, h_5$都有可能被清零，输出层的计算无法过度依赖$h_1, \\ldots, h_5$中的任一个，从而在训练模型时起到正则化的作用，并可以用来应对过拟合。在测试模型时，我们为了拿到更加确定性的结果，一般不使用丢弃法\n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5jd69in3m.png?imageView2/0/w/960/h/960)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_698weeu",
    "id": "53FBE46C03C040D0A123E957865CEC6A",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 丢弃法从零开始的实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "graffitiCellId": "id_0cw2xsh",
    "id": "30FE9592111F415A8C913AC04AD9BF9A",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.4.0\n"
     ]
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import numpy as np\n",
    "import sys\n",
    "sys.path.append(\"..\")\n",
    "import d2lzh1981 as d2l\n",
    "\n",
    "print(torch.__version__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "graffitiCellId": "id_7mt4bcl",
    "id": "C6790DFD4650485AB8315E04E12D4C74",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def dropout(X, drop_prob):\n",
    "    X = X.float()\n",
    "    assert 0 <= drop_prob <= 1\n",
    "    keep_prob = 1 - drop_prob\n",
    "    # 这种情况下把全部元素都丢弃\n",
    "    if keep_prob == 0:\n",
    "        return torch.zeros_like(X)\n",
    "    mask = (torch.rand(X.shape) < keep_prob).float()\n",
    "    \n",
    "    return mask * X / keep_prob"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "graffitiCellId": "id_ek4ildz",
    "id": "F961F801B5CB434683F8F82FD79C8F23",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.],\n",
       "        [ 8.,  9., 10., 11., 12., 13., 14., 15.]])"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.arange(16).view(2, 8)\n",
    "dropout(X, 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "graffitiCellId": "id_i67qnbo",
    "id": "A2563ED1062D48728E6AA868A3A8C3F4",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0.,  0.,  0.,  6.,  8., 10.,  0., 14.],\n",
       "        [ 0.,  0., 20.,  0.,  0.,  0., 28.,  0.]])"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dropout(X, 0.5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "graffitiCellId": "id_gwsj0hd",
    "id": "56DF0D9E4EE84D04A6CCE5180FF9D164",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0., 0., 0., 0., 0., 0., 0., 0.],\n",
       "        [0., 0., 0., 0., 0., 0., 0., 0.]])"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dropout(X, 1.0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "graffitiCellId": "id_w81sasb",
    "id": "E3ECEB59A5F944898BE2C5ABEB513208",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 参数的初始化\n",
    "num_inputs, num_outputs, num_hiddens1, num_hiddens2 = 784, 10, 256, 256\n",
    "\n",
    "W1 = torch.tensor(np.random.normal(0, 0.01, size=(num_inputs, num_hiddens1)), dtype=torch.float, requires_grad=True)\n",
    "b1 = torch.zeros(num_hiddens1, requires_grad=True)\n",
    "W2 = torch.tensor(np.random.normal(0, 0.01, size=(num_hiddens1, num_hiddens2)), dtype=torch.float, requires_grad=True)\n",
    "b2 = torch.zeros(num_hiddens2, requires_grad=True)\n",
    "W3 = torch.tensor(np.random.normal(0, 0.01, size=(num_hiddens2, num_outputs)), dtype=torch.float, requires_grad=True)\n",
    "b3 = torch.zeros(num_outputs, requires_grad=True)\n",
    "\n",
    "params = [W1, b1, W2, b2, W3, b3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "graffitiCellId": "id_d24i59y",
    "id": "C3C7D8DC21FA471AA4AF11DFAC41D7E5",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "drop_prob1, drop_prob2 = 0.2, 0.5\n",
    "\n",
    "def net(X, is_training=True):\n",
    "    X = X.view(-1, num_inputs)\n",
    "    H1 = (torch.matmul(X, W1) + b1).relu()\n",
    "    if is_training:  # 只在训练模型时使用丢弃法\n",
    "        H1 = dropout(H1, drop_prob1)  # 在第一层全连接后添加丢弃层\n",
    "    H2 = (torch.matmul(H1, W2) + b2).relu()\n",
    "    if is_training:\n",
    "        H2 = dropout(H2, drop_prob2)  # 在第二层全连接后添加丢弃层\n",
    "    return torch.matmul(H2, W3) + b3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "graffitiCellId": "id_ticmy78",
    "id": "73C1F705FAA14F4390B8D24CCF9E5673",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def evaluate_accuracy(data_iter, net):\n",
    "    acc_sum, n = 0.0, 0\n",
    "    for X, y in data_iter:\n",
    "        if isinstance(net, torch.nn.Module):\n",
    "            net.eval() # 评估模式, 这会关闭dropout\n",
    "            acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()\n",
    "            net.train() # 改回训练模式\n",
    "        else: # 自定义的模型\n",
    "            if('is_training' in net.__code__.co_varnames): # 如果有is_training这个参数\n",
    "                # 将is_training设置成False\n",
    "                acc_sum += (net(X, is_training=False).argmax(dim=1) == y).float().sum().item() \n",
    "            else:\n",
    "                acc_sum += (net(X).argmax(dim=1) == y).float().sum().item() \n",
    "        n += y.shape[0]\n",
    "    return acc_sum / n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "graffitiCellId": "id_ryzllq8",
    "id": "B493E72017B54831A80790EE0AA3DB2C",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss 0.0046, train acc 0.549, test acc 0.704\n",
      "epoch 2, loss 0.0023, train acc 0.785, test acc 0.737\n",
      "epoch 3, loss 0.0019, train acc 0.825, test acc 0.834\n",
      "epoch 4, loss 0.0017, train acc 0.842, test acc 0.763\n",
      "epoch 5, loss 0.0016, train acc 0.848, test acc 0.813\n"
     ]
    }
   ],
   "source": [
    "num_epochs, lr, batch_size = 5, 100.0, 256  # 这里的学习率设置的很大，原因与之前相同。\n",
    "loss = torch.nn.CrossEntropyLoss()\n",
    "train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size, root='/home/kesci/input/FashionMNIST2065')\n",
    "d2l.train_ch3(\n",
    "    net,\n",
    "    train_iter,\n",
    "    test_iter,\n",
    "    loss,\n",
    "    num_epochs,\n",
    "    batch_size,\n",
    "    params,\n",
    "    lr)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_ar5qzrs",
    "id": "99EEA36EC08E471E8EC87F0AF6FCEF34",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 简洁实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "graffitiCellId": "id_t8mnig0",
    "id": "28E345EC41EB48D8876B6A15A3E18FBD",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "net = nn.Sequential(\n",
    "        d2l.FlattenLayer(),\n",
    "        nn.Linear(num_inputs, num_hiddens1),\n",
    "        nn.ReLU(),\n",
    "        nn.Dropout(drop_prob1),\n",
    "        nn.Linear(num_hiddens1, num_hiddens2), \n",
    "        nn.ReLU(),\n",
    "        nn.Dropout(drop_prob2),\n",
    "        nn.Linear(num_hiddens2, 10)\n",
    "        )\n",
    "\n",
    "for param in net.parameters():\n",
    "    nn.init.normal_(param, mean=0, std=0.01)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "graffitiCellId": "id_iba0hj1",
    "id": "2EDA1430541148BB863DC9071ED92323",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss 0.0046, train acc 0.553, test acc 0.736\n",
      "epoch 2, loss 0.0023, train acc 0.785, test acc 0.803\n",
      "epoch 3, loss 0.0019, train acc 0.818, test acc 0.756\n",
      "epoch 4, loss 0.0018, train acc 0.835, test acc 0.829\n",
      "epoch 5, loss 0.0016, train acc 0.848, test acc 0.851\n"
     ]
    }
   ],
   "source": [
    "optimizer = torch.optim.SGD(net.parameters(), lr=0.5)\n",
    "d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_m2ujou7",
    "id": "88258E5A8E1B4FCAA576FB7FB1AAC42C",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 总结\n",
    "\n",
    "- 欠拟合现象：模型无法达到一个较低的误差\n",
    "    \n",
    "- 过拟合现象：训练误差较低但是泛化误差依然较高，二者相差较大\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
